package top.lv666.graduation_design_serve.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;

public class JWTUtils {
    private static final String KEY = "lvzeqi666TOP.COMPAssWORd = 1154884776648！！~~~~~";

    /**
     * @apiNote 生成token
     */

    public static String getToken(HashMap<String, String> hashMap) {
        //设置过期时间 60*60*3=>3小时
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60 * 60 * 3);
        //获取token
        JWTCreator.Builder builder = JWT.create();
        hashMap.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        return builder
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(KEY));

    }


    /**
     * @apiNote 验证token
     */
    public static Boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            throw new Error("无效签名");
        } catch (TokenExpiredException e) {
            throw new Error("token过期");
        } catch (AlgorithmMismatchException e) {
            throw new Error("token解密算法错误");
        } catch (Exception e) {
            throw new Error("token无效");
        }
    }

    /**
     * @apiNote 根据token解析获取数据信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
    }

}
